﻿using UnityEngine;

//------------------------------------------------------------
// shaco Framework
// Copyright © 2017-2025 chang.liu All rights reserved.
// Feedback: 449612236@qq.com
//------------------------------------------------------------

namespace shaco
{
    [System.Serializable]
    public struct OrientedBounds
    {
        public Vector3 center;
        public Vector3 extents;
        public Vector3 size => extents * 2;
        public Quaternion rotation => null == _trans ? Quaternion.identity : _trans.rotation;

        [SerializeField]
        Transform _trans;

        static public OrientedBounds FromTransform(Transform trans)
        {
            var retValue = new OrientedBounds();
            retValue._trans = trans;
            retValue.center = trans.position;
            retValue.extents = Vector3.Scale(trans.lossyScale, trans.localScale) * 0.5f;
            return retValue;
        }
        static public OrientedBounds FromTransform(Transform trans, Bounds localBounds)
        {
            var retValue = new OrientedBounds();
            retValue._trans = trans;
            retValue.center = localBounds.center;
            retValue.extents = localBounds.extents;
            return retValue;
        }
        static public OrientedBounds FromRenderer(Renderer render)
        {
            var retValue = new OrientedBounds();
            retValue.center = render.bounds.center;
            var v1 = render.localBounds.extents;
            var v2 = render.transform.lossyScale;
            retValue.extents = new Vector3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z);
            retValue._trans = render.transform;
            return retValue;
        }

        // 分离轴定理实现相交检测
        public bool Intersects(OrientedBounds other)
        {
            return _trans.Intersects(other._trans, new Bounds(center, size), new Bounds(other.center, other.size));
        }
    }
}